package org.example.demo.broker;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


public class Demo {
    private static final ThreadLocal<List<String>> HOLDER = ThreadLocal.withInitial(ArrayList::new);
    private static final List<String> FAKE_HOLDER = new CopyOnWriteArrayList<>();
    private static final AtomicInteger COUNT = new AtomicInteger(0);

    public static void add(String msg) {
        HOLDER.get().add(msg);
    }

    public static List<String> getAndClear() {
        List<String> data = HOLDER.get();
        HOLDER.remove();
        return data;
    }

    public static void fakeAdd(String msg) {
        FAKE_HOLDER.add(msg);
    }

    public static List<String> fakeGetAndClear() {
        return FAKE_HOLDER;
    }

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2,
                2,
                2,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10)
        );
        for (int i = 0; i < 2; i++) {
            Runnable runnable = () -> {
                for (int i1 = 0; i1 < 2; i1++) {
                    Demo.fakeAdd(Thread.currentThread().getName() + ": " + i1);
                    COUNT.addAndGet(1);
                    System.out.println(COUNT.get());
                }
            };
            Thread thread = new Thread(runnable);
            thread.setName("thread-" + i);
            executor.submit(thread);
        }
    }
}
